package servlets;


import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import java.util.zip.Adler32;
import java.util.zip.CheckedInputStream;
import java.util.zip.Checksum;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import clientRequest.ClientRequest;

import commands.AddFileCommand;


/**
 * UploadServlet implementation class ServerServlet - for upload a file
 * urls: .../UploadServlet + .../UploadServlet/*
 */

public class UploadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
 
	private AddFileCommand addFileCommand = new AddFileCommand();
	
	/**
	 * init
	 */
	public void init(ServletConfig config) throws ServletException {}


	/**
	 * do nothing
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setContentType("text/html");
        response.setStatus(HttpServletResponse.SC_OK);        
	}

	/**
	 * urls: /UploadServlet - upload a file to the dropbox root
	 *       /UploadServlet/folder/folderName - upload a file to the this folder
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	    PrintWriter out = response.getWriter();
	    response.setContentType("text/plain");
	    
	    //get the user name and the password from the session
        String userID = (String) request.getSession().getAttribute("userID");
        String password = (String) request.getSession().getAttribute("password");
        
        //get the folder name
        String folderName = request.getRequestURI().substring(request.getRequestURI().lastIndexOf("/")+1);
     
        //mark if the folder is the dropbox root
        boolean isMyDropBox=true;
        
        if (request.getRequestURI().contains("/folder"))
        	isMyDropBox=false;        	
	    
	    
	    //http://www.geekinterview.com/question_details/17234
		DiskFileItemFactory  fileItemFactory = new DiskFileItemFactory ();
 
		ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
		uploadHandler.setHeaderEncoding("UTF-8");
		
		out.println("<html>");
        out.println("<head>");
        out.println("<title> clever dropbox =) </title>");
        out.println("</head>");
        out.println("<body bgcolor=#66CCFF>");
        
		try {
			
			//Parse the request			 
			List<FileItem> items = uploadHandler.parseRequest(request);
            String name =null;
            byte[] data =null;
            long checksum;

			Iterator itr = items.iterator();
			while(itr.hasNext()) {
				FileItem item = (FileItem) itr.next();
				
				if (!item.isFormField())
				{
					name = item.getName();
					//if there is really a file (the field is not empty)
					if (!name.equals(""))
					{
						//get the file and add it
		                data = item.get();
		                checksum = getChecksum(item.getInputStream());
		                ClientRequest clientRequest = new ClientRequest(userID,"ENTRY_CREATE",name,"\\"+folderName+"\\"+name,data, checksum ,false,isMyDropBox,true);
		                addFileCommand.action(clientRequest);
					}
				}
			}
			
			out.println("<br><h3 align='center'>your file upload succeed</h3>");

		}catch(FileUploadException ex) {
			//log("Error encountered while parsing the request",ex);
			out.println("<h3>the file upload failed</h3>");
		} catch(Exception ex) {
			 out.println("<h3>the file upload failed</h3>");
			//log("Error encountered while uploading file",ex);
		}
		
		//return to the folder page
		if (isMyDropBox)
			out.println("<a href='/UserDropboxServlet'> <h3 align='center'> back </h3> </a>");			
		else
			out.println("<a href='/UserDropboxServlet/folder/" + folderName +"'> <h3 align='center'> back </h3> </a>");
 
		out.println("</body>");
        out.println("</html>");
        
        out.close();
		
	}
	
	//compute file checksum
	 private long getChecksum(InputStream is)
	 {
		 //http://www.roseindia.net/tutorial/java/corejava/zip/AdlerCheckSum.html
		 
		 CheckedInputStream cis = null;
		  Checksum checksum = new Adler32();

	     try 
	     {
	         cis = new CheckedInputStream(is, checksum);
	         byte[] tempBuf = new byte[128];
	         while (cis.read(tempBuf) >= 0) {}                
	     }
	     catch (Exception e)
	     {
	         throw new RuntimeException(e);
	     }
	     finally
	     {
	         if (cis != null)
	         {
	             try
	             {
	                 cis.close();
	             }
	             catch (IOException ioe) {}
	             cis = null;
	         }
	         if (is != null)
	         {
	             try
	             {
	                 is.close();
	             }
	             catch (IOException ioe) {}
	             is = null;
	         }
	     }
	     return checksum.getValue();
	 }
	
}
